package com.iyao_app.mvp.signlist;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.AlphaAnimation;
import com.amap.api.maps.model.animation.AnimationSet;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.iyao_app.R;
import com.iyao_app.adapter.SignListAdapter_;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.PageInfo;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.StoryData;
import com.iyao_app.entry.StoryDetail;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.util.Contants;
import com.iyao_app.util.ToastUtil;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.TimeUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import github.chenupt.dragtoplayout.AttachUtil;
import github.chenupt.dragtoplayout.DragTopLayout;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/12/11.
 */

public class CustomListWithMapActivity extends BaseActivityWithHead implements OnLoadmoreListener , AMapLocationListener {


    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_next)
    ImageView mIvNext;
    @BindView(R.id.lin_qian_dao)
    LinearLayout mLinQianDao;
    @BindView(R.id.lin_ling_di)
    LinearLayout mLinLingDi;
    @BindView(R.id.mapView)
    TextureMapView mMapView;
    @BindView(R.id.top_view)
    LinearLayout mTopView;
    @BindView(R.id.x_recyclerView)
    RecyclerView mXRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.drag_content_view)
    LinearLayout mDragContentView;
    @BindView(R.id.drag_layout)
    DragTopLayout mDragLayout;
    private int page = 1;
    private PageInfo pageInfo;
    private final int pageSize = 10;

    private AMap aMap;
    private String id;
    private SignListAdapter_ adapter;
    private LatLng currentLng;
    private BitmapDescriptor myDescrip;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_map);
        ButterKnife.bind(this);
        init(savedInstanceState);
    }

    private void init(@Nullable Bundle savedInstanceState) {
        id = getIntent().getStringExtra(Contants.TYPE);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        adapter = new SignListAdapter_(null);
        mXRecyclerView.setAdapter(adapter);
        mXRecyclerView.setLayoutManager(layoutManager);
        mXRecyclerView.setNestedScrollingEnabled(false);
        mRefreshLayout.setOnLoadmoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadmore(true);
//        setNextImage(R.mipmap.);
        setTitleTV("签到");
        mDragLayout.setOverDrag(false);
        mDragLayout.toggleTopView();
        mDragLayout.closeTopView(false);
        initMap(savedInstanceState);
        mXRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                mDragLayout.setTouchMode(AttachUtil.isRecyclerViewAttach(recyclerView));

            }
        });
        getData(true);
    }


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    private void location() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);


        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);


        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(false);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
//        myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//连续定位、且将视角移动到地图中心点，定位蓝点跟随设备移动。（1秒1次定位）
//        //        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//连续定位、且将视角移动到地图中心点，地图依照设备方向旋转，定位点会跟随设备移动。（1秒1次定位）
//        //        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
//        myLocationStyle.strokeColor(Color.TRANSPARENT);
//        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_my_location));
//        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style

        //启动定位
        mLocationClient.startLocation();
    }
    private void initMap(Bundle savedInstanceState) {
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        blackMap();
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(false);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.getUiSettings().setZoomControlsEnabled(false);
//        aMap.getUiSettings().setAllGesturesEnabled(false);
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        location();
    }


    private void blackMap() {
        try {
            //开启自定义样式
            aMap.setMapCustomEnable(true);
            //加载个性化的地图底图数据
            aMap.setCustomMapStylePath(Environment.getExternalStorageDirectory()
                    + File.separator + "style/mystyle_sdk_1511952973_0100.data");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        for (Marker marker : aMap.getMapScreenMarkers()) {

            marker.remove();
        }
        mMapView.onDestroy();


    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        blackMap();
    }

    private boolean noMore = false;

    private void getData(final boolean isRefesh) {
        if (isRefesh) {
            page = 1;
        } else {
            page++;
        }
        NetUtils.getInstance().getEventList(id, null, "1", page, pageSize, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        StoryData storyData = model.getModel();
                        if (storyData != null) {
                            List<StoryDetail> list = storyData.list;
                            pageInfo = storyData.pageInfo;
                            if (pageInfo.pageTotal <= page) {
                                noMore = true;
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                noMore = false;
                            }
                            if (isRefesh) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (list == null || list.size() == 0) {

                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                if (isRefesh) {
                                    adapter.getData().clear();
                                }

                                dealData(list,isRefesh);
                            }
                        }
                    }

                }
            }

            @Override
            public void onFail(String message, int code) {
                if (isRefesh) {
                    mRefreshLayout.finishRefresh();
                } else {
                    mRefreshLayout.finishLoadmore();
                }
            }
        }, StoryData.class);
    }

    private void dealData(final List<StoryDetail> list,final boolean isRefesh) {
        if (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) {
                    StoryDetail temp = list.get(i - 1);
                    StoryDetail storyDetail = list.get(i);
                    boolean sameDay = TimeUtils.isSameDay(temp.createTime, storyDetail.createTime);
                    if (sameDay) {
                        storyDetail.isNotDayStart = true;
                    }
                }
            }
        }
        adapter.addData(list);

        if (noMore) {
            StoryDetail data = new StoryDetail();
            data.isLast = true;
            adapter.addData(data);
        }

        Observable.fromArray(adapter.getData()).concatMap(new Function<List<StoryDetail>, ObservableSource<StoryDetail>>() {
            @Override
            public ObservableSource<StoryDetail> apply(List<StoryDetail> persons) throws Exception {

                return Observable.fromIterable(list);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<StoryDetail>() {
                    @Override
                    public void accept(StoryDetail o) throws Exception {
                        downLoadImg(o);
                    }
                });
    }
    private void downLoadImg(final StoryDetail o) {
        final View coverView = LayoutInflater.from(CustomListWithMapActivity.this).inflate(R.layout.cover_item_, null);
        final CircleImageView coverHead = coverView.findViewById(R.id.cover_head);

        Glide.with(this).load(o.avatarUrl).asBitmap().override(100, 100).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                //bitmap即为下载所得图片
                coverHead.setImageBitmap(resource);
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(coverView);
                MarkerOptions markerOption = new MarkerOptions();
                markerOption.position(new LatLng(o.latitude, o.longitude));
                markerOption.draggable(false);//设置Marker可拖动
                markerOption.icon(bitmapDescriptor);
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                markerOption.setFlat(false);//设置marker平贴地图效果
                markerOption.anchor(0.5f, 1.0f);

                AnimationSet animationSet = new AnimationSet(true);
                com.amap.api.maps.model.animation.ScaleAnimation scaleAnimation = new com.amap.api.maps.model.animation.ScaleAnimation(0, 1, 0, 1);
                AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
                animationSet.addAnimation(alphaAnimation);
                animationSet.addAnimation(scaleAnimation);
                long duration = 1000L;
                animationSet.setDuration(duration);
                animationSet.setInterpolator(new BounceInterpolator());
                Marker marker = aMap.addMarker(markerOption);
                marker.setAnimation(animationSet);
                marker.setTitle(String.valueOf(o.id));
                marker.startAnimation();
                resource.recycle();
            }
        });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        getData(false);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
            LogUtil.e("定位失败");
            ToastUtil.showToast(this, "获取当前位置信息失败!");
            return;
        }
        if (aMapLocation.getErrorCode() == 0) {
            if (currentLng == null) {
                currentLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());


                setLocationChange(currentLng);
            } else {
                if (currentLng.latitude == aMapLocation.getLatitude() && currentLng.longitude == aMapLocation.getLongitude()) {//坐标一样
                    LogUtil.e("定位坐标一样");
                } else {
                    currentLng = null;

                    currentLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    setLocationChange(currentLng);
                }
            }
        }
    }

    private void setLocationChange(LatLng currentLng) {
        //清除所有maker
        aMap.clear();
        drawMyLocation(currentLng);
    }

    private void drawMyLocation(final LatLng latLng) {
        //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 0, 0));
        //AMap类中提供，带有移动过程的动画
        aMap.animateCamera(mCameraUpdate, 500, new AMap.CancelableCallback() {
            @Override
            public void onFinish() {
                if (myDescrip == null) {
                    myDescrip = BitmapDescriptorFactory.fromResource(R.mipmap.ic_my_location);
                }
                MarkerOptions markerOption = new MarkerOptions();
                markerOption.position(latLng);
                markerOption.draggable(false);//设置Marker可拖动
                markerOption.icon(myDescrip);
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                markerOption.setFlat(false);//设置marker平贴地图效果
                markerOption.anchor(0.5f, 0.5f);
                Marker marker = aMap.addMarker(markerOption);
                marker.setTitle("我的位置");

            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationClient != null)
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }
}
